﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Net.NetworkInformation;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.Configuration;

namespace jNetServer
{
    public class NetServer : BaseWebServer
    {
        public NetServer(string serverRoot, string root, int port, bool isAutoPort, string index)
        {
            ServerRoot = serverRoot;
            WebRoot = root;
            Port = port;
            IsAutoPort = isAutoPort;
            Indexs = index;

            if (IsAutoPort)
            {
                Port = AutoPort(Port);
            }
        }

        public override bool Start()
        {
            ServerRoot = Application.StartupPath;
            string net = ConfigurationManager.AppSettings["net"].ToString();

            try
            {
                ServerProcess = new Process();
                ServerProcess.StartInfo.Arguments = String.Format("/port:{0} /path:{1} /vpath:{2}", Port, WebRoot, "/");
                ServerProcess.StartInfo.WorkingDirectory = ServerRoot;
                ServerProcess.StartInfo.FileName = ServerRoot + @"\" + net;
                ServerProcess.StartInfo.RedirectStandardInput = true; //重定向标准输入
                ServerProcess.StartInfo.RedirectStandardOutput = true; //重定向标准输出
                ServerProcess.StartInfo.RedirectStandardError = true; //重定向错误输出
                ServerProcess.StartInfo.UseShellExecute = false;
                ServerProcess.StartInfo.CreateNoWindow = true;
                ServerProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                return ServerProcess.Start();
            }
            catch
            {
                return false;
            }
        }

        public override void OpenHome()
        {
            string[] indexs = Indexs.Split(' ');

            string url = string.Format("http://localhost:{0}/{1}", Port, indexs[0]);
            ServerWebBrowser = Process.Start(url);
        }
    }
}
